#coding: utf-8

import requests, json

import db as PageDb

db = PageDb.PageDb('system')

from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

"""
统一管理微信接口请求
"""

class Mp():
	def __init__(self, appid): # appid也可以是企业微信的corpid_agent_id
		self.appid = appid
		self.type = {
			# 获取公众号渠道二维码ticket
			'GET_MP_TICKET': ['cgi-bin/qrcode/create?access_token=ACCESS_TOKEN', 'POST'],
			# # 根据ticket获取二维码
			# 'GET_MP_QRCODE': ['cgi-bin/showqrcode']
			# 小程序发送订阅消息
			'SUB_MSG': ['cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN', 'POST'],
			# 发送小程序模板消息
			'TEMPLATE_SEND': ['cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN', 'POST'],
			# 公众号发送模板消息
			'MP_TEMPLATE_SEND': ['cgi-bin/message/template/send?access_token=ACCESS_TOKEN', 'POST'],
			# 发送客服消息
			'CUSTOM_SEND': ['cgi-bin/message/custom/send?access_token=ACCESS_TOKEN', 'POST'],
			# 用户信息获取
			'USER_INFO': ['cgi-bin/user/info?access_token=ACCESS_TOKEN', 'GET'],
			# 发送预览
			'PREVIEW': ['cgi-bin/message/mass/preview?access_token=ACCESS_TOKEN', 'POST'],
			# 发送图文
			'SEND_ALL': ['cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN', 'POST'],
			# 查看图文发送状态
			'MASS_GET': ['cgi-bin/message/mass/get?access_token=ACCESS_TOKEN', 'POST'],
			# 素材数量
			'MATERIAL_COUNT' : ['cgi-bin/material/get_materialcount?access_token=ACCESS_TOKEN', 'GET'],
			# 新增永久素材
			'ADD_MATERIAL': ['cgi-bin/material/add_material', 'POST'],
			# 删除永久素材
			'DEL_MATERIAL': ['cgi-bin/material/del_material?access_token=ACCESS_TOKEN', 'POST'],
			# 获取永久素材
			'BARCHGET_MATERIAL': ['cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN', 'POST'],
			# 新增图文永久素材
			'ADD_NEWS': ['cgi-bin/material/add_news?access_token=ACCESS_TOKEN', 'POST'],
			# 获取阅读数
			'GET_ARTICLETOTAL': ['/datacube/getarticletotal?access_token=ACCESS_TOKEN', 'POST'],
			# 菜单删除
			'MENU_DELETE': ['cgi-bin/menu/delete?access_token=ACCESS_TOKEN', 'GET'],
			# 菜单查询
			'MENU_GET': ['cgi-bin/menu/get?access_token=ACCESS_TOKEN', 'GET'],
			# 菜单创建
			'MENU_CREAT': ['cgi-bin/menu/create?access_token=ACCESS_TOKEN', 'POST'],

			'COMMENT_LIST': ['cgi-bin/comment/list?access_token=ACCESS_TOKEN', 'POST'],

			'COMMENT_MARKELECT': ['cgi-bin/comment/markelect?access_token=ACCESS_TOKEN', 'POST'],
			# 删除群发
			'MASS_DELETE': ['cgi-bin/message/mass/delete?access_token=ACCESS_TOKEN', 'POST'],


			# 企业微信发送消息
			'CORP_MESSAGE_SEND': ['/cgi-bin/message/send?access_token=ACCESS_TOKEN', 'POST']
		}
		self.selected_type = ''

	def httpCall(self, url_type, args=None):
		self.selected_type = url_type
		t = self.type[url_type]
		short_url = t[0]
		method = t[1]
		response = {}

		if 'POST' == method:
			url = self.__makeUrl(short_url)
			response = self.__httpPost(url, args)
		elif 'GET' == method:
			url = self.__makeUrl(short_url)
			response = self.__httpGet(url, args)

		if self.__tokenExpired(response.get('errcode')):
			print("===>error", response, url, args)
			# exit()
			return False
		else:
			return response

	def __httpPost(self, url, args):
		if not isinstance(args, str):
			args = json.dumps(args).decode('unicode-escape').encode('utf-8')
		real_url = self.__appendToken(url)
		r = requests.post(real_url, data=args, verify=False)
		r.encoding = 'utf-8'
		return r.json()

	def __httpGet(self, url, args):
		real_url = self.__appendToken(url)
		r = requests.get(real_url, params=args, verify=False)
		r.encoding = 'utf-8'
		return r.json()

	def __makeUrl(self, short_url):
		if self.selected_type.startswith('CORP'):
			base = "https://qyapi.weixin.qq.com"
		else:
			base = "https://api.weixin.qq.com"
			
		return base + short_url if short_url[0] == '/' else base + '/' + short_url

	def __appendToken(self, url):
		if self.selected_type.startswith('CORP'):
			return url.replace('ACCESS_TOKEN', db.get_qytoken(self.appid))
		return url.replace('ACCESS_TOKEN', db.get_actoken(self.appid))

	@staticmethod
	def __tokenExpired(errCode) :
		if errCode == 40014 or errCode == 42001 or errCode == 42007 or errCode == 42009 :
			return True
		else :
			return False



